<template><!-- 纯净视频页面 -->
  <div class="pure" :style="bgImagUrl ? {backgroundImage: `url(${bgImagUrl})`} : {} ">
    <div class="upper-part">
      <!-- 头部返回分享组件 -->
      <HeaderPure :handleInvitationCard="handleInvitationCard" :isFollow="isFollow" @formChildMsg='formChildData' />
      <!-- 主播信息组件 -->
      <Anchor @formChildMsg='formChildData' :isFollow="isFollow" :videoInfo="videoInfo" />
    </div>
    <div class="videoBox" @click="playStatus(2)">
      <!-- 视频播放器组件 -->
      <VideoCom ref="videoCom" type="hScreen" status="liveback" :videoInfo="videoInfo.videoInfo"
        :progressShow="progressShow" :playBtnShow="playBtnShow" :progressL="progressL" :courseInfo="courseInfo"
        :playBtn="playBegin" @playStatus="playStatus" @getProgress="getProgress" @getVideoLoading="getVideoLoading"
        :isToolBar="false" />
    </div>
    <div class="lower-half">
      <!-- 底部互动组件 -->
      <Interactive :handlePopupsShow="handlePopupsShow" :goodsList="goodsList" :videoId="videoId" :likeCount="likeCount"
        :columnData="columnData" :isLike="isLike" :isCollect="isCollect" @formChildMsg='formChildData' />
      <!-- 进度条组件 -->
      <ProgressBar v-show="isProgressBar" :progressShow="progressShow" :playBtnShow="playBtnShow" :progress="progress"
        :changeSpeedOut="changeSpeedOut" @changeProgress="changeProgress" />
      <!-- 视频介绍组件 -->
      <DescCom :title="videoInfo.videoInfo.title" />
      <!-- 视频标签组件 -->
      <VideoTag :tagData="tagData" />
      <!-- 商品组件 -->
      <Goods :handlePopupsShow="handlePopupsShow" :goodsList="goodsList" @formChildMsg='formChildData' />
    </div>

    <!-- 邀请卡 -->
    <InvitationCard v-if='isInvitationCard' @formChildMsg='formChildData' fromComPage = "back" :liveInfo="videoInfo.videoInfo"
      :fromCom="fromCom" />
    <canvas class="canvas-box" ref="canvasBox" id="canvasBox"></canvas>
    <!-- 商品橱窗弹出层 -->
    <van-popup v-model="ShopPopupsShow" :close-on-click-overlay="ShopPopupsObj.isPopupGlobalMask"
      :round="ShopPopupsObj.round" :position="ShopPopupsObj.position" overlay-class="popClass"
      :overlay='ShopPopupsObj.isOverlay' :style="{width:ShopPopupsObj.width, height:ShopPopupsObj.height }"
      @click-overlay="clickVanOverlay">
      <ShopWindow :goodsList="goodsList" @formChildMsg='formChildData'/>
    </van-popup>
    <!-- 购物车购买风险弹窗 -->
    <BuyRisk v-if="isBuyRisk" :buyRiskObj ="buyRiskObj" :shoppingLinkInfo="shoppingLinkInfo" @formChildMsg="formChildData" />
    <!-- 第三方外链返回按钮 -->
    <BackHomePage v-if="isJump" :toJump="toJump" />
  </div>
</template>

<script>
  import wxApi from "@/util/wxApi";
  import dayjs from 'dayjs';
  import liveBackMixin from "@/mixins/liveBackMixin.js"
  import Anchor from './compoments/anchor.vue'; // 主播信息组件
  import DescCom from './compoments/desc.vue'; // 视频介绍组件
  import Goods from './compoments/goods.vue'; // 商品组件
  import HeaderPure from './compoments/headerPure.vue'; // 头部返回分享组件
  import Interactive from './compoments/interactive.vue'; // 底部互动组件
  import ProgressBar from './compoments/progressBar.vue'; // 进度条组件
  import VideoTag from './compoments/videoTag.vue'; // 视频标签组件
  import ShopWindow from './compoments/shopWindow.vue'; // 商品橱窗组件
  import VideoCom from '@/components/videoCom.vue'; // 视频播放组件
  import InvitationCard from '@/pages/invitationCard/newInvitationCard.vue'; // 邀请卡组件
  import BackHomePage from '@/components/backHomePage' // 三方外链返回首页按钮
  import defaultBackImg from '@/assets/images/pureVideo/DefaultBack.png' // 默认背景图
  import fun from "@/util/function";
  import { shoppingInfo, getFollowState, followSpecialColumn, cancelFollowSpecialColumn, queryLikeCount, collectOrLike, cancelCollectOrLike, queryColumnList, shoppingRiskTip, isCheckUserAuthShoppingPop, shoppingDotNum } from '@/util/api.js';

  export default {
    mixins: [ wxApi, liveBackMixin ],
    props: {
      videoInfo: Object,
      courseInfo: Object,
    },
    components: {
      Anchor, // 主播信息组件
      DescCom, // 视频介绍组件
      Goods, // 商品组件
      HeaderPure, // 头部返回分享组件
      Interactive, // 互动组件
      ProgressBar, // 进度条组件
      VideoCom, // 视频播放器组件
      VideoTag, // 视频标签组件
      ShopWindow, // 商品橱窗组件
      InvitationCard, // 展示邀请卡组件
      BackHomePage, // 三方外链返回首页按钮
    },
    data() {
      return {
        videoId: this.$route.params.id,
        bgImagUrl: '', // 背景图
        tagData: [], // 视频标签
        columnData: [], // 所属专栏
        ShopPopupsShow: false, // 商品弹出层
        goodsList: [], // 商品橱窗数据
        isInvitationCard: false, //展示邀请卡组件
        banner: [],
        txBase: '', //用户头像
        reduceVal: 1200,
        ShopPopupsObj: { // 弹出层配置
          'position': 'bottom',
          'width': '',
          'height': '',
          'isOverlay': true,
          'round': true,//圆角
          'isPopupGlobalMask': true,//蒙层是否点击消失
        },
        isFollow: false, // 是否关注
        isCollect: false, // 是否收藏
        isLike: false, // 是否点赞
        likeCount: 0, // 视频点赞数
        fromCom: 'vLookBack',
        progressShow: false, //播放进度展示
        progress: 0, // 进度条
        progressL: 0, // 拖动进度条的长度
        playBtnShow: false, // 视频播放状态
        isPlayBtn: true, // 播放按钮
        isProgressBar: true, // 进度条是否显示
        isJump: false, // 是否为第三方外链进入
        toJump: '', //从那个机构跳转过来
        isBuyRisk: false,// 是否打开购物车购买风险弹窗
        buyRiskObj:{},
        shoppingLinkInfo:{},// 购物车当前点击商品信息
      }
    },
    watch: {
      "$store.state.currTime": {
        handler: function (newVal) {
          const time = ((newVal / this.$store.state.duration) * 100).toFixed(2)
          this.getProgress(time)
        }
      },
      uinfo(curVal, oldVal) {
        if (curVal.un != undefined && curVal.un.length > 0) {
          this.un = curVal.un;
          this.nickname = curVal.nickname;
          this.wxpic = curVal.wxpic;
          this.getCardER(); //邀请里面二维码
          this.invitationCardFun(this.wxpic);
        }
      },
      isLoadIcon(val, oldVal) {},
    },
    computed: {
      isLoadIcon() {
        if (this.$store.state.SysOrgInfo.icon) {
          this.wxRegister(this.wxRegCallback);
          return true;
        } else {
          return false;
        }
      },
    },
    async created() {
      const { videoInfo: { video, labels, partnerId, partnerType, tags } } = this.videoInfo;
      // 判断为横屏竖屏
	    const videoObj = document.createElement('video')
	    videoObj.preload = 'metadata';
	    videoObj.src = video;
	    videoObj.onloadedmetadata = function (e) {
	      URL.revokeObjectURL(video)
	      const width = videoObj.videoWidth;
	      const height = videoObj.videoHeight;
        videoObj.remove();
        const videoBox = document.querySelector('.videoBox');
        if (height > width) {
          videoBox.style.top = '0';
          videoBox.style.height = '100%';
        }
	    };
      // 设置视频url
      if (video) this.$store.dispatch("videoSrc", video);
      // 设置视频标签
      if (partnerType === 11) { 
        if (labels) this.tagData = labels.split(',').slice(0, 3);
      } else {
        if (tags.length > 0) this.tagData = tags.map(item => item.tagName)
      }
      // 设置背景图
      this.bgImagUrl = this.videoInfo.videoInfo.bgImagUrl || defaultBackImg //直播大背景图
      // 查询是否关注机构
      partnerType === 11 
        ? this.getInteraction(1).then((res) => this.isFollow = res) 
        : this.getInteraction(6).then((res) => this.isFollow = res)
      // 查询是否收藏直播间
      this.getInteraction(3).then((res) => this.isCollect = res)
      // 查询是否点赞视频
      this.getInteraction(5).then((res) => this.isLike = res)
      // 查询视频点赞数量
      this.queryLikeNum()
      if (partnerType === 11) {
        if (this.videoInfo.videoInfo.roomVideoExt2.goodsList) {
          this.goodsList = this.videoInfo.videoInfo.roomVideoExt2.goodsList.map(item => {
            return {
              id: item.goodsId,
              imgUrl: require('@/assets/images/pureVideo/DefaultGoods.png'),
              title: item.goodsName,
              link: goodsLink,
            }
          })
        }
      } else {
        this.getShoppingData()
      }
      if (window.terminal.isZxjtApp) {
        this.banner = [
          {
            url: require('@/assets/images/inviteApp/1.png'),
            title: "蓝色简约"
          },
          {
            url: require('@/assets/images/inviteApp/2.png'),
            title: "限时抢购"
          },
          {
            url: require('@/assets/images/inviteApp/3.png'),
            title: "看直播赢好礼"
          },
          {
            url: require('@/assets/images/inviteApp/4.png'),
            title: "标准版"
          },
          {
            url: require('@/assets/images/invite/5.png'),
            title: "建投版邀请卡"
          },
        ]
      } else {
        this.banner = [
          {
            url: require('@/assets/images/invite/1.png'),
            title: "蓝色简约"
          },
          {
            url: require('@/assets/images/invite/2.png'),
            title: "限时抢购"
          },
          {
            url: require('@/assets/images/invite/3.png'),
            title: "看直播赢好礼"
          },
          {
            url: require('@/assets/images/invite/4.png'),
            title: "标准版"
          },
          {
						url: require('@/assets/images/invite/5.png'),
						title: "建投版邀请卡"
					},
        ]
      }
      if (this.$store.state.userInfo.un != undefined && this.$store.state.userInfo.un.length > 0) { //im 消息初始化
        this.un = this.$store.state.userInfo.un;
        this.nickname = this.$store.state.userInfo.nickname;
        this.wxpic = this.$store.state.userInfo.wxpic;
        this.getCardER(); //邀请里面二维码
        this.invitationCardFun(this.wxpic);
      }
      // 查询所属专栏
      try {
        const res = await queryColumnList({ itemId: partnerId });
        const { code, data, msg } = res.data;
        if (code === '000000') {
          this.columnData = data.items;
        }
      } catch (error) {
        throw new Error(error);
      }
      // 是否为三方外链跳转
      if (!!window.sessionStorage.getItem('isJump')) {
        this.isJump = !!window.sessionStorage.getItem('isJump')
        this.toJump = window.sessionStorage.getItem('toJump')
      }
      //中信建投进入视频详情页打点
      this.sensorsTrack()
    },
    mounted() {
    },
    methods: {
      // 显示商品弹窗
      handlePopupsShow() {
        this.ShopPopupsShow = true;
      },
      // 点击分享
      handleInvitationCard() {
        if (this.$store.state.isYk) {//游客
          let jointUrl = fun.getCurPageUrl('back', this.$route.params.id)
          fun.ykDisposeFun(jointUrl)
        } else { //非游客
          if (window.terminal.isZxjtApp) {
            this.getInviteBgList();
          } else if (window.terminal.isZxjtqhApp) {//建投期货app   
            let { shareTitle, shareSubtitle, shareImgurl, } = this.videoInfo.videoInfo
            fun.zxjtqhShare('liveRoom', "22,23,24,1", shareTitle, fun.getCurPageUrl('back', this.videoId), shareSubtitle, shareImgurl)
          } else {
            this.isInvitationCard = true;
          }
          this.functionTrack('转发')//分享打点
        }
      },
      // 分享...
      getInviteBgList() {
        let { videoInfo: { roomId } } = this.videoInfo;
        if (!roomId) {//空
          let canvasBox = document.getElementById('canvasBox')
          let canvas = document.createElement('canvas')
          canvas.width = 646;
          canvas.height = 992;
          canvasBox.appendChild(canvas);
          this.drawImg('建投版邀请卡')
          canvas.style.display = 'none';
        } else {
          this.$http.get('/h5live/getShardingImg?roomId=' + roomId).then((res) => {
            let {
              code,
              data
            } = res.data
            if (code == '000000') {
              if (data.length && data.length == '1') {
                let canvasBox = document.getElementById('canvasBox')
                let canvas = document.createElement('canvas')
                  canvas.width = 646;
                  canvas.height = 992;
                  canvasBox.appendChild(canvas);
                  this.drawImg(data[0].title, data)
                  canvas.style.display = 'none';
              } else {
                throw new Error('app邀请卡接口返回错误');
              }
            }
          }, (err) => {
            throw new Error(err);
          })
        }
      },
      // 分享...
      drawImg(title, dataArray) {
        let erCode = this.$lockr.get("ERcode")
        this.imgBase64ERcode = jrQrcode.getQrBase64(erCode, {
          correctLevel: QRErrorCorrectLevel.L,
        }); //base64格式二维码
        return new Promise((resolve, reject) => {
          switch (title) {
            case '蓝色简约': //绘制第一张
              let c = document.getElementById("canvasBox");
              let ctx = c.getContext("2d");
              const bg = new Image();
              bg.src = this.banner[0].url;
              bg.onload = () => {
                c.width = 646 * 2;
                c.height = 992 * 2;
                ctx.drawImage(bg, 0, 0, 646 * 2, 992 * 2);
                const TXImg = new Image();
                TXImg.src = this.txBase;
                TXImg.onload = () => {
                  fun.circleImg(ctx, TXImg, 270 * 2, 134 * 2, 106);
                  // ctx.drawImage(TXImg, c.width/2 - 51, 173, 104, 104); //起始   +大小
                  ctx.fillStyle = "#FFFFFF"; //昵称
                  ctx.font = "normal small-caps 500 72px Microsoft Yahei In-Bold Font";
                  ctx.textAlign = "center";
                  ctx.fillText(this.nickname, 323 * 2, 290 * 2);
                  const SCImg = new Image(); //直播主题图片
                  SCImg.src = this.postImg;
                  SCImg.onload = () => {
                    ctx.drawImage(SCImg, 75 * 2, 367 * 2, 496 * 2, 280 * 2); //起始   +大小
                    //绘制二维码
                    const ERImg = new Image();
                    ERImg.src = this.imgBase64ERcode;
                    ERImg.onload = () => {
                      ctx.drawImage(ERImg, 397 * 2, 696 * 2, 172 * 2, 172 * 2);
                      fun.dealImage(c.toDataURL("image/png"),
                        this.reduceVal, (res) => {
                          //this.canvasImg = res
                          this.postAppShare(res);
                          c.style.display = 'none';
                        })
                    }
                  }
                }
              }
              break;
            case '限时抢购': //绘制第二张
              let c1 = document.getElementById("canvasBox");
              let ctx1 = c1.getContext("2d");
              const bg1 = new Image();
              bg1.src = this.banner[1].url;
              bg1.onload = () => {
                c1.width = 646 * 2;
                c1.height = 996 * 2;
                ctx1.drawImage(bg1, 0, 0, 646 * 2, 996 * 2);
                const TXImg = new Image();
                TXImg.src = this.txBase;
                TXImg.onload = () => {
                  fun.circleImg(ctx1, TXImg, 273 * 2, 197 * 2, 99);
                  // ctx1.drawImage(TXImg, c1.width/2 - 51, 230, 104, 104); //起始   +大小
                  ctx1.fillStyle = "#FFFFFF"; //昵称
                  ctx1.font = "normal small-caps 500 72px Microsoft Yahei In-Bold Font";
                  ctx1.textAlign = "center";
                  ctx1.fillText(this.nickname, 323 * 2, 338 * 2);
                  const SCImg = new Image(); //直播主题图片
                  SCImg.src = this.postImg;
                  SCImg.onload = () => {
                    ctx1.drawImage(SCImg, 75 * 2, 425 * 2, 496 * 2, 280 * 2); //起始   +大小
                    //绘制二维码
                    const ERImg = new Image();
                    ERImg.src = this.imgBase64ERcode;
                    ERImg.onload = () => {
                      ctx1.drawImage(ERImg, 397 * 2, 752 * 2, 172 * 2, 172 * 2);
                      fun.dealImage(c1.toDataURL(
                        "image/png"), this
                        .reduceVal, (
                          res) => {
                        //this.canvasImg = res
                        this.postAppShare(res);
                        c1.style.display = 'none'
                      })
                    }
                  }
                }
              }
              break;
            case '看直播赢好礼': // 绘制第三张
              let c2 = document.getElementById("canvasBox");
              let ctx2 = c2.getContext("2d");
              const bg2 = new Image();
              bg2.src = this.banner[2].url;
              bg2.onload = () => {
                c2.width = 646 * 2;
                c2.height = 996 * 2;
                ctx2.drawImage(bg2, 0, 0, 646 * 2, 996 * 2);
                const TXImg = new Image();
                TXImg.src = this.txBase;
                TXImg.onload = () => {
                  fun.circleImg(ctx2, TXImg, 82 * 2, 228 * 2, 99);
                  // ctx2.drawImage(TXImg, 74, 324, 82, 82); //起始   +大小
                  ctx2.fillStyle = "#FFFFFF"; //昵称
                  ctx2.font = "normal small-caps 500 72px Microsoft Yahei In-Bold Font";
                  ctx2.textAlign = "left";
                  ctx2.fillText(this.nickname, 213 * 2, 260 * 2);
                  const SCImg = new Image(); //直播主题图片
                  SCImg.src = this.postImg;
                  SCImg.onload = () => {
                    ctx2.drawImage(SCImg, 75 * 2, 367 * 2, 496 * 2, 280 * 2); //起始   +大小
                    //绘制二维码
                    const ERImg = new Image();
                    ERImg.src = this.imgBase64ERcode;
                    ERImg.onload = () => {
                      ctx2.drawImage(ERImg, 397 * 2, 695 * 2, 172 * 2, 172 * 2);
                      fun.dealImage(c2.toDataURL(
                        "image/png"), this
                        .reduceVal, (
                          res) => {
                        //this.canvasImg = res
                        this.postAppShare(res);
                        c2.style.display = 'none';
                      })

                    }
                  }
                }

              }
              break;
            case '标准版': // 绘制第四张
              let c3 = document.getElementById("canvasBox");
              let ctx3 = c3.getContext("2d");
              const bg3 = new Image();
              bg3.src = this.banner[3].url;
              bg3.onload = () => {
                c3.width = 646 * 2;
                c3.height = 996 * 2;
                ctx3.drawImage(bg3, 0, 0, 646 * 2, 996 * 2);
                const TXImg = new Image();
                TXImg.src = this.txBase;
                TXImg.onload = () => {
                  fun.circleImg(ctx3, TXImg, 58 * 2, 193 * 2, 116);
                  // ctx3.drawImage(TXImg, 30, 134, 116, 116); //起始   +大小
                  ctx3.fillStyle = "#000000"; //昵称
                  ctx3.font = "normal small-caps 500 72px Microsoft Yahei In-Bold Font";
                  ctx3.textAlign = "left";
                  ctx3.fillText(this.nickname, 207 * 2, 233 * 2);
                  const SCImg = new Image(); //直播主题图片
                  SCImg.src = this.postImg;
                  SCImg.onload = () => {
                    ctx3.drawImage(SCImg, 55 * 2, 352 * 2, 539 * 2, 305 * 2); //起始   +大小
                    //绘制二维码
                    const ERImg = new Image();
                    ERImg.src = this.imgBase64ERcode;
                    ERImg.onload = () => {
                      ctx3.drawImage(ERImg, 422 * 2, 723 * 2, 172 * 2, 172 * 2);
                      fun.dealImage(c3.toDataURL("image/png"), this
                        .reduceVal, (res) => {
                          //this.canvasImg = res
                          this.postAppShare(res);
                          c3.style.display = 'none'
                        })

                    }
                  }
                }
              }
              break;
            case '建投版邀请卡': // 绘制第五张`
						  let c31 = document.getElementById("canvasBox");
							let ctx31 = c31.getContext("2d");
							const bg31 = new Image();
							bg31.src = this.banner[4].url;
							bg31.onload = () => {
								c31.width = 646*2;
								c31.height = 992*2;
								ctx31.drawImage(bg31, 0, 0, 646*2, 992*2);
									const SCImg = new Image(); //直播主题图片
									SCImg.src = this.postImg;
									SCImg.onload = () => {
										const {name,icon} = this.$store.state.SysOrgInfo || {};	
										const  curUrl = window.location.href;
										let shareTitleCur;
										let shareSubTitleCur;
										if(curUrl.includes('liveRoom')){//直播间  
											const {shareTitle,shareDesc,shareIcon} = this.$store.state.orgShareObj || {};//机构分享						
											const {intro,title,shareTitel:roomShareTitel,shareSubtitle:roomShareSubtitl,shareImgurl:roomShareImgurl} = this.roomInfo.roomInfo;
											shareTitleCur =  roomShareTitel || title || shareTitle ||` 【 ${name} 】一起来看直播吧！`  // 分享标题
											shareSubTitleCur =  roomShareSubtitl || shareDesc ||  `精彩直播,尽在 ${name}手机直播！`  //分享描述
										}else{//回看
											const { shareTitle: orgShareTitle, shareDesc, shareIcon } = this.$store.state.orgShareObj || {};//机构分享
											const  { shareTitle, shareSubtitle, shareImgurl, subTitle, title }  = this.videoInfo.videoInfo;
											shareTitleCur = shareTitle || title || orgShareTitle || `【 ${name } 】精彩视频`; //分享标题
											shareSubTitleCur = shareSubtitle ||  shareDesc || `精彩视频,尽在${name}手机直播！`; //分享描述
										}
										fun.drawRoundRectTopRightLeft(ctx31,20*2,0,0,646*2, 365*2,SCImg)											
											//绘制title
											ctx31.fillStyle = "#000000";
											ctx31.font = "80px Arial";
											ctx31.fillText(shareTitleCur.length > 14 ? shareTitleCur.slice(0,14)+'...' : shareTitleCur, 30*2, 435*2);
											//绘制副标题
											ctx31.fillStyle = "#222630";
											ctx31.font = "52px Arial";
											fun.textPrewrap(ctx31,shareSubTitleCur,30*2, 500*2,40*2,550*2,2);
												//绘制时间
												ctx31.fillStyle = "#ff5a00";
												ctx31.font = "80px Arial";
                        const { roomId ,beginTime ,crtTime} = this.videoInfo.videoInfo;
											  const time = dayjs(roomId ? beginTime : crtTime).format("MM月DD日 HH:mm");
												ctx31.fillText(time, 30*2, 675*2);
												//绘制开播时间
												ctx31.fillStyle = "#ff5a00";
												ctx31.font = "48px Arial";
												//ctx31.fillText(roomId?'开播时间':'上传时间', 42*2, 598*2);
                        ctx31.fillText('开播时间', 42*2, 598*2);
												//绘制圆角矩形
												ctx31.lineWidth = 2;//边框为14px
												ctx31.strokeStyle = '#ff5a00';
												ctx31.beginPath();
												ctx31.roundRect(30*2, 570*2, 120*2, 40*2, 20);//x,y width height  rad
												ctx31.stroke();			
											//绘制二维码
											const ERImg = new Image();
											ERImg.src = this.imgBase64ERcode;
											ERImg.onload = () => {
												ctx31.drawImage(ERImg, 478*2, 816*2, 300, 300);
												fun.dealImage(c31.toDataURL("image/png"), this
													.reduceVal, (res) => {
														this.canvasImg = res
														this.postAppShare(res);
														c31.style.display = 'none'
													}
                        )
											}
									}						
							}
            break;
            default: //自定义
              let c4 = document.getElementById("canvasBox");
              c4.width = 646 * 2;
              c4.height = 996 * 2;
              let ctx4 = c4.getContext("2d");
              let bg4 = new Image();
              fun.getBase64(dataArray[0].imgUrl, '', function (res) {
                bg4.src = res
              });
              bg4.onload = () => {
                ctx4.drawImage(bg4, 0, 0, 646 * 2, 796 * 2);
                const mengCeng = new Image();
                mengCeng.src = this.mengCengApp;
                mengCeng.onload = () => {
                  ctx4.drawImage(mengCeng, 0, 463 * 2, 646 * 2, 529 * 2); //起始   +大小
                  const TXImg1 = new Image();
                  TXImg1.src = this.txBase;
                  TXImg1.onload = () => {
                    fun.circleImg(ctx4, TXImg1, 28 * 2, 828 * 2, 100);
                    ctx4.fillStyle = "#000000"; //昵称
                    ctx4.font = "normal small-caps 500 60px Microsoft Yahei In-Bold Font";
                    ctx4.fillText(this.nickname, 148 * 2, 858 * 2);
                    const ERImg = new Image();
                    ERImg.src = this.imgBase64ERcode;
                    ERImg.onload = () => {
                      ctx4.drawImage(ERImg, 474 * 2, 807 * 2, 145 * 2, 145 * 2);
                      fun.dealImage(c4.toDataURL("image/png"), this.reduceVal, (res) => {
                        //this.canvasImg = res;
                        this.postAppShare(res);
                        c4.style.display = 'none'
                      })
                    }
                  }
                }
              }
              break;
          }
        })
      },
      // 分享...
      postAppShare(base64Pic) {
        base64Pic = base64Pic.slice(23); //删除data:image/jpeg;base64,
        if (!base64Pic) return console.log('canvas 生成base64为空');
        let shareUrl = fun.getCurPageUrl('back', this.videoId);
        let {
          videoInfo: {
            shareTitle,
            title,
            shareSubtitle
          }
        } = this.videoInfo;
        //分享
        let shareTitleLive = shareTitle || title;
        let summary = shareSubtitle || title;
        if (window.terminal.isZxjtAndroid) {
          KDS_Native.shareLive(shareTitleLive, shareUrl, summary, base64Pic)
        } else if (window.terminal.isZxjtIos) {
          let json = {
            "title": shareTitleLive,
            "shareUrl": shareUrl,
            "summary": summary,
            "base64Pic": base64Pic
          }
          window.webkit.messageHandlers.shareLive.postMessage(json)
        }
      },
      // 分享...
      invitationCardFun(txImg) {
        if (!this.$store.state.isYk) { //非游客
          if (txImg == null || txImg.includes('gd_mr')) { //游客容错
            this.txBase = require('@/assets/images/gd_mr.png')
          } else {
            this.getImgBase64(txImg, 'tx');
          };

          let {
            videoInfo: {
              imagUrl
            }
          } = this.videoInfo;
          //封面图 img
          this.getImgBase64(imagUrl, 'back');
        }
      },
      // 本地将url转成base64格式
      getImgBase64(url, source) {
        window.fun.getBase64(url, source, (res) => {
          if (source === "back") {
            this.postImg = res; // 将结果赋值给需要用的变量属性
          } else {
            this.txBase = res;
          }
        })
      },
      // 邀请里面二维码
      getCardER() {
				let ERcode = fun.getCurPageUrl("back", this.videoId)
				this.$lockr.set("ERcode", ERcode)
			},
      // 请求商品数据
      async getShoppingData() {
        try {
          const msgData = await shoppingInfo(this.videoId, '1');
          const { code } = msgData.data;
          if (code === '000000') {
            const { data, data: { goods: { goodsList } } } = msgData.data;
            this.goodsList = goodsList;
          }
        } catch (error) {
          throw new Error(error);
        }
      },
      getVideoLoading(val) {
        this.videoLoading = val
      },
      // 倍速修改
      changeSpeedOut(speed) {
        this.$refs.videoCom.player.setSpeed(speed)
      },
      // 监听视频进度
      getProgress(val) {
        this.progress = val
      },
      // 改变视频时间
      changeProgress(val) {
        if (this.playBtnShow) this.playStatus(1) // 暂停时播放视频
        this.progress = val
        const { player } = this.$refs.videoCom
        player.seek(player.getDuration() * (val / 100))
      },
      // 改变视频播放状态
      playStatus(val) { // val 1 播放   val 2 暂停
        if (val === 1) {
          this.playBtnShow = false;
          this.$store.commit("setVideoState", "playVideo");
        } else {
          this.playBtnShow = true;
          this.$store.commit("setVideoState", "stopVideo");
        }
      },
      playBtn() {
        this.playBegin();
      },
      playBegin() { //开始播放
        if (this.courseInfo) {
          //priceType  0-免费，1-付费  haveBuy true 购买 false 未购买
          const { haveBuy } = this.courseInfo;
          if (!haveBuy) {
            fun.toastMessage('若需观看请前往中信建投期货金建投APP“精品课程”栏目订阅该课程');
            return
          }
        }
        this.progressShow = true
        this.isVideoDom = true; //视频 dom显示
        this.isPlayBtn = false;
        this.$store.commit("setVideoState", "playVideo")
      },
      // 查询是否关注机构/订阅专栏/收藏视频/收藏直播间/点赞视频  value  1-关注机构 2-订阅专栏 3-收藏视频 4-收藏直播间 5-点赞视频 6-关注机构(直播小站)
      async getInteraction(value) {
        const { videoInfo: { creator } } = this.videoInfo;
        let businessId
        if (value === 1) {
          const { videoInfo: { roomVideoExt2: { corpCode } } } = this.videoInfo;
          businessId = corpCode;
        } else if (value === 6) {
          businessId = creator;
        } else {
          businessId = this.videoId;
        }
        try {
          const res = await getFollowState(businessId, value);
          return res.data.data;
        } catch (error) {
          throw new Error(error);
        }
      },
      // 查询更新点赞数量
      async queryLikeNum() {
        try {
          const res = await queryLikeCount(this.videoId, this.$channel);
          this.likeCount = res.data.data;
        } catch (error) {
          throw new Error(error);
        }
      },
      // 微信分享
      wxRegCallback() {
        const { shareTitle: orgShareTitle, shareDesc, shareIcon } = this.$store.state.orgShareObj || {};//机构分享
        const { videoInfo: { shareTitle, shareSubtitle, shareImgurl, subTitle, title } } = this.videoInfo;
        const { SysOrgInfo: { icon, name } } = this.$store.state;       
        let opstion = {
          link: fun.getCurPageUrl('back', this.videoId),
          title: shareTitle || title || orgShareTitle || '【' + name + '】精彩视频', //分享标题
          desc: shareSubtitle || subTitle || shareDesc || "精彩视频，尽在" + name + "手机直播！" , //分享描述
          imgUrl: shareImgurl || shareIcon || icon, //分享的图片 
          success: ()=> {
            fun.shareDotNumFun({ ...this.videoInfo.videoInfo, fromTypeLiveBack:'back', vid:this.videoId });//打点
          },
          error: (e)=> {
            fun.shareDotNumFun({ ...this.videoInfo.videoInfo, fromTypeLiveBack:'back', vid:this.videoId });//打点
          }
        };
        this.ShareTimeline(opstion);
      },
      // 操作集合
      async formChildData(childData) {
        switch (childData.type) {
          case 'follow': // 关注
            if (this.$store.state.isYk) { //游客
						  fun.ykDisposeFun();
						  return;
						}
            try {
              const { videoInfo: { creator, partnerType } } = this.videoInfo;
              let res
              if (partnerType === 11) {
                const { videoInfo: { roomVideoExt2: { corpCode } } } = this.videoInfo;
                res = await followSpecialColumn(corpCode, 1)
              } else {
                res = await followSpecialColumn(creator, 6)
              }
              const { code, data, msg } = res.data;
              if (code === '000000') {
                this.functionTrack('关注')//关注埋点
                fun.toastMessage('已关注')
                this.isFollow = true;
              } else {
                fun.toastMessage(msg);
              }
            } catch (error) {
              throw new Error(error);
            }
            break;
          case 'cancelFollow': // 取消关注
            try {
              const { videoInfo: { creator, partnerType } } = this.videoInfo;
              let res
              if (partnerType === 11) {
                const { videoInfo: { roomVideoExt2: { corpCode } } } = this.videoInfo;
                res = await cancelFollowSpecialColumn(corpCode, 1)
              } else {
                res = await cancelFollowSpecialColumn(creator, 6)
              }
              const { code, data, msg } = res.data;
              if (code === '000000') {
                fun.toastMessage('已取消关注')
                this.isFollow = false;
              } else {
                fun.toastMessage(msg);
              }
            } catch (error) {
              throw new Error(error);
            }
            break;
          case 'collect': // 收藏
            if (this.$store.state.isYk) { //游客
						  fun.ykDisposeFun();
						  return;
						}
            try {
              const res = await collectOrLike(this.videoId, 3, this.$channel)
              const { code, data, msg } = res.data;
              if (code === '000000') {
                fun.toastMessage('已收藏')
                this.isCollect = true;
                childData.callback()
                this.functionTrack('收藏')//收藏打点
              } else {
                fun.toastMessage(msg);
              }
            } catch (error) {
              throw new Error(error);
            }
            break;
          case 'cancelCollect': // 取消收藏
            try {
              const res = await cancelCollectOrLike(this.videoId, 3, this.$channel)
              const { code, data, msg } = res.data;
              if (code === '000000') {
                this.isCollect = false;
                childData.callback()
              } else {
                fun.toastMessage(msg);
              }
            } catch (error) {
              throw new Error(error);
            }
            break;
          case 'like': // 点赞
            if (this.$store.state.isYk) { //游客
						  fun.ykDisposeFun();
						  return;
						}
            try {
              const res = await collectOrLike(this.videoId, 5, this.$channel)
              const { code, data, msg } = res.data;
              if (code === '000000') {
                this.functionTrack('点赞')//点赞打点
                childData.callback()
                this.queryLikeNum()
                this.isLike = true;
              } else {
                fun.toastMessage('当前为游客模式');
              }
            } catch (error) {
              throw new Error(error);
            }
            break;
          case 'cancelLike': // 取消点赞
            try {
              const res = await cancelCollectOrLike(this.videoId, 5, this.$channel)
              const { code, data, msg } = res.data;
              if (code === '000000') {
                childData.callback()
                this.queryLikeNum()
                this.isLike = false;
              } else {
                fun.toastMessage(msg);
              }
            } catch (error) {
              throw new Error(error);
            }
            break;
          case 'closeInvitation': //关闭邀请卡组件
            this.isInvitationCard = false;
            break;
          case 'columnClick':
            this.functionTrack('专栏')//点击专栏按钮打点
            break;
          case 'goShop':
            this.getGoodsRiskTip(childData.item)
            this.functionTrack('去购买', childData.id, childData.title)//在商品橱窗组件中点击购买打点
            break;
          case 'goInstitution':
            this.functionTrack('发布人点击')//发布人点击打点
            break;
          case 'openBuyRisk': // 打开购物车购买风险弹窗
            this.buyRiskObj = childData.data.buyRiskObj
            this.shoppingLinkInfo = childData.data.shoppingLinkInfo
            this.isBuyRisk = true;
            break;
          case 'closeBuyRisk': // 购物车购买风险弹窗 点击记录
            this.isBuyRisk = false;
            break;
          default:
            console.log('传入 Type 无效')
            break;
        }
      },
      //视频详情页打点
      sensorsTrack() {
        $sensorsTrack('financing_videoZoneVideoDetailsPageView', {
          video_id: this.$route.params.id,
          video_name:this.videoInfo.videoInfo.title
        });
      },
      //视频功能按钮打点
      functionTrack(functionName,code = '',name = '') {
        $sensorsTrack('financing_videoDetailsPageFunctionClick', {
          video_id: this.$route.params.id,
          video_name: this.videoInfo.videoInfo.title,
          product_code: code,
          product_name: name,
          content_writer: this.videoInfo.videoInfo.userAnchor.nickname,
          function_name: functionName
        });
      },
      // 商品跳转
      shoppingLinkFun(item){
        if (window.terminal.isZxjtApp) {
          fun.zxjtAppLink(item);          
        } else {
          window.location.href = item.link;
        }
      },
      //购买风险弹窗内容
      async getGoodsRiskTip(item) {
        //打点
        const { id } = item;
        //goods:{商品ID}:{type,1-直播,2-回看}:{roomId/videoId}
        const params = {
          'id': `goods:${id}:${window.location.href.includes('liveRoom') ? 1 : 2}:${this.$route.params.roomid || this.$route.params.id}`,
          'plat': fun.getPlatform()
        }
        shoppingDotNum(params)
        try {
          const type = window.location.href.includes('liveRoom') ? 0 : 1
          const msgData = await shoppingRiskTip(this.videoId, type)
          //enPopUpWin 是否需要验证
          const { code, data } = msgData.data;
          if (code === '000000') {
            if (data) {
              const buyRiskObj = data;
              const { enPopUpWin } = data;
              if (enPopUpWin) {//true 开
                //查询是否授权过
                const msg = await isCheckUserAuthShoppingPop(this.roomId, this.type);
                const { code, data } = msg.data
                if (code === '000000') {
                  if (data) {//已经授权
                    this.shoppingLinkFun(item)
                  } else {//未授权
                    this.formChildData({
                      type: 'openBuyRisk',
                      data: { buyRiskObj, shoppingLinkInfo: { item } }
                    })
                  }
                }
              } else {
                this.shoppingLinkFun(item)
              }
            } else {
              this.shoppingLinkFun(item)
            }
          }
        } catch (error) {
          throw new Error(error)
        }
      },
    },
  }
</script>

<style scoped lang="less">
  .pure {
    width: 100%;
    height: 100%;
    position: relative;
    background: #000000;
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .canvas-box {
      width: 646px;
      height: 992px;
      margin: 0 auto;
      background: white;
      display: none;
      position: absolute;
      top: 20px;
      left: 20px;
      z-index: 2222;
      border-radius: 26px;
    }

    .upper-part {
      width: 100%;
      z-index: 6;
      display: flex;
      flex-direction: column;
    }

    .lower-half {
      width: 100%;
      z-index: 6;
      display: flex;
      flex-direction: column-reverse;
    }

    .videoBox {
      width: 100%;
      height: 424px;
      position: absolute;
      top: 13rem;
      left: 0;
      display: flex;
      justify-content: center;
      align-items: center;

      .play {
        position: absolute;
        width: 100px;
        height: 100px;
        background: url('../../../../assets/images/pureVideo/play.png') no-repeat;
        background-size: 100% 100%;
        z-index: 1100;
      }
    }

  }
</style>